#!/bin/sh
# Copyright (C) 2013 Jolla Oy
# Contact: Pekka Lundstrom  <pekka.lundstrom@jollamobile.com>
#
# This adds oneshot job to be run durint preinit
# usage: add-oneshot <path-of-your-script> [<more paths>]
# Path has to point to existing executable file

[ -z "$1" ] && echo "add-preinit-oneshot: No jobs defined - FAIL" && exit 1

# Define PATH in case we are called in build time (PATH empty or sbin not included)
if [ -z "$PATH" ] ||
   [[ "$PATH" != *sbin* ]]; then
    PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin"
fi

set +e

while [ -n "$1" ]; do
    JOB=$1
    # Job must exist and it must be executable
    [ ! -x $JOB ] && echo "add-preinit-oneshot: $JOB does not exist - FAIL" && exit 2
    # Create link so we run this job later in preinit
    SAVE_OK=""
    JOB_NAME=$(basename $JOB)
    ln -sf $JOB /etc/oneshot.d/preinit/$JOB_NAME && SAVE_OK="1"
    if [ -n "$SAVE_OK" ]; then
        echo "add-preinit-oneshot: /etc/oneshot.d/preinit/$JOB_NAME - job saved OK"
    else
        echo "add-preinit-oneshot: /etc/oneshot.d/preinit/$JOB_NAME - job saving FAILED"
    fi
    shift
done
exit 0
